<template>
  <t-form
    ref="form"
    :class="['item-container', `login-${type}`]"
    :data="formData"
    :rules="FORM_RULES"
    label-width="0"
    @submit="onSubmit"
  >
    <template v-if="type == 'password'">
      <t-form-item name="username">
        <t-input v-model="formData.username" size="large" :placeholder="t('pages.login.input.username')">
          <template #prefix-icon>
            <t-icon name="user" />
          </template>
        </t-input>
      </t-form-item>

      <t-form-item name="password">
        <t-input
          v-model="formData.password"
          size="large"
          :type="showPsw ? 'text' : 'password'"
          clearable
          :placeholder="t('pages.login.input.password')"
        >
          <template #prefix-icon>
            <t-icon name="lock-on" />
          </template>
          <template #suffix-icon>
            <t-icon :name="showPsw ? 'browse' : 'browse-off'" @click="showPsw = !showPsw" />
          </template>
        </t-input>
      </t-form-item>

      <div class="check-container remember-pwd">
        <t-checkbox>{{ t('pages.login.remember') }}</t-checkbox>
        <span class="tip">{{ t('pages.login.forget') }}</span>
      </div>
    </template>

    <!-- 扫码登录 -->
    <template v-else-if="type == 'qrcode'">
      <div class="tip-container">
        <span class="tip">{{ t('pages.login.wechatLogin') }}</span>
        <span class="refresh">{{ t('pages.login.refresh') }} <t-icon name="refresh" /> </span>
      </div>
      <qrcode-vue value="" :size="160" level="H" />
    </template>

    <!-- 注册 -->
    <template v-else>
      <t-form ref="registerFormRef" style="width: 100%" :rules="registerRules" :data="registerForm" label-align="top">
        <t-row style="width: 100%" :gutter="[16, 16]">
          <t-col :span="6">
            <t-form-item label="公司名称" name="companyName">
              <t-input v-model="registerForm.companyName" placeholder="请输入公司名称" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="法人姓名" name="legalPerson">
              <t-input v-model="registerForm.legalPerson" placeholder="请输入法人姓名" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="法人身份证" name="idCard">
              <t-input v-model="registerForm.idCard" placeholder="请输入法人身份证" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="联系电话/账号" name="contactPhone">
              <t-input v-model="registerForm.contactPhone" placeholder="请输入联系电话" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="密码" name="password">
              <t-input v-model="registerForm.password" type="password" placeholder="请输入密码" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="公司地址" name="companyAddress">
              <t-input v-model="registerForm.companyAddress" placeholder="请输入公司地址" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="邮箱" name="email">
              <t-input v-model="registerForm.email" placeholder="请输入注册邮箱" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="营业执照" name="businessLicense">
              <common-upload
                v-model:value="registerForm.businessLicense"
                :value-type="'data'"
                :limit="1"
                tip="请上传营业执照"
              />
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item class="btn-container">
              <t-button block size="large" @click="onRegister"> 立即注册</t-button>
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>
    </template>

    <t-form-item v-if="type === 'password'" class="btn-container">
      <t-button block size="large" type="submit"> {{ t('pages.login.signIn') }} </t-button>
    </t-form-item>

    <div class="switch-container">
      <span v-if="type !== 'password'" class="tip" @click="switchType('password')">{{
        t('pages.login.accountLogin')
      }}</span>
      <span v-if="type !== 'qrcode'" class="tip" @click="switchType('qrcode')">{{ t('pages.login.wechatLogin') }}</span>
      <span v-if="type !== 'register'" class="tip" @click="switchType('register')">注册成为供货商</span>
    </div>
  </t-form>
</template>

<script setup lang="ts">
import QrcodeVue from 'qrcode.vue';
import type { FormInstanceFunctions, FormRule, SubmitContext } from 'tdesign-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';
import { computed, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { insertApi } from '@/api/supplier_application';
import CommonUpload from '@/components/common-upload/index.vue';
import { t } from '@/locales';
import { useUserStore } from '@/store';

const userStore = useUserStore();

const INITIAL_DATA = {
  username: '',
  password: '',
};

const FORM_RULES: Record<string, FormRule[]> = {
  username: [{ required: true, message: t('pages.login.required.username'), type: 'error' }],
  password: [{ required: true, message: t('pages.login.required.password'), type: 'error' }],
};

const type = ref('password');

const form = ref<FormInstanceFunctions>();
const formData = ref({ ...INITIAL_DATA });
const showPsw = ref(false);

const switchType = (val: string) => {
  type.value = val;
};

const router = useRouter();
const route = useRoute();

const onSubmit = async (ctx: SubmitContext) => {
  if (ctx.validateResult === true) {
    try {
      await userStore.login(formData.value);

      MessagePlugin.success('登录成功');
      const redirect = route.query.redirect as string;
      const redirectUrl = redirect ? decodeURIComponent(redirect) : '/dashboard';
      router.push(redirectUrl);
    } catch (e) {
      console.log(e);
      MessagePlugin.error(e.message);
    }
  }
};
// 注册
const registerForm = ref({
  companyName: '',
  legalPerson: '',
  idCard: '',
  contactPhone: '',
  companyAddress: '',
  businessLicense: '',
  password: '',
  email: '',
});
const registerRules = computed(() => ({
  companyName: [{ required: true, message: '请输入公司名称' }],
  legalPerson: [{ required: true, message: '请输入法人姓名' }],
  idCard: [{ required: true, message: '请输入法人身份证' }],
  contactPhone: [{ required: true, message: '请输入联系电话' }],
  companyAddress: [{ required: true, message: '请输入公司地址' }],
  businessLicense: [{ required: true, message: '请上传营业执照' }],
  password: [{ required: true, message: '请输入密码' }],
  email: [{ required: true, message: '请输入邮箱' }],
}));
const registerFormRef = ref(null);
const onRegister = async () => {
  try {
    const valid = await registerFormRef.value.validate();
    if (valid === true) {
      await insertApi(registerForm.value);
      MessagePlugin.success('申请提交成功,请等待审核通过！');
      router.push('/login');
    }
  } catch (e) {
    console.log(e);
  }
};
</script>

<style lang="less" scoped>
@import '../index.less';
</style>
